<?php
/**
 * mp
 * User: wayne
 * Date: 2015-09-11
 */
namespace Wx\Model;
use Think\Model;

class WxReplyModel extends Model {
    /* 组织模型自动验证 */
    protected $_validate = array (
        array('mp_id', 'require', '公众号信息不能为空', self::MUST_VALIDATE, '', self::MODEL_INSERT),
        array('reply_type', 'require', '类型不能为空', self::MUST_VALIDATE, '', self::MODEL_INSERT)
    );

    /**
     * 根据公众号号id和类型
     * 
     * @param integer $mp_id
     * @param string $reply_type
     */
    public function getReply($mp_id, $reply_type) {
        return $this->where(array('mp_id' => $mp_id, 'reply_type' => $reply_type))->find();
    }
    
    /**
     * 添加|编辑回复
     * 
     * @param array $reply_data
     */
    public function compileReply(array $reply_data) {
        //查看是否有记录
        $reply_info = $this->where(array('mp_id' => $reply_data['mp_id'], 'reply_type' => $reply_data['reply_type']))->find();
        
        //如果有
        if($reply_info){
            $result = $this->where(array('mp_id' => $reply_data['mp_id'], 'reply_type' => $reply_data['reply_type']))->save($reply_data);
        
            if($result === false){
                $this->error = '修改回复内容失败';
                return false;
            }
        
            return $reply_info['mp_id'];
        }
        
        return $this->add($reply_data);
    }
    
    /**
     * 获取用户拥有的公众号
     * 
     * @param string $uid
     */
    public function getByUid($uid) {
//         $sql = "select wea.*,m.nickname,m.header from {$this->tablePrefix}wx_mp as wea
//                 left join {$this->tablePrefix}member as m on wea.uid = m.uid
//                 where wea.status <> 4 and wea.uid={$uid}";
//         if(!is_null($organiz_id)){
//             $sql .= ' and wea.organiz_id = '.$organiz_id;
//         }else{
//             $sql .= ' and wea.organiz_id = 0';
//         }
//         return $this->query($sql);
        return $this->where(array('uid' => $uid))->select();
    }

    /**
     * 获得公众号列表
     */
    public function getPublicByMpid($mpids){
        $sql = "select wea.*,m.nickname,m.header,o.name from {$this->tablePrefix}wx_ent_app as wea
                left join {$this->tablePrefix}member as m on wea.uid = m.uid
                left join {$this->tablePrefix}organization as o on wea.organiz_id = o.id
                where wea.status <> 4 and wea.mp_id in (".implode(',',$mpids).")";

        return $this->query($sql);
    }

    /**
     * 解除托管
     */
    public function removeTG($mp_id, $uid){
        return $this->where(array('mp_id'=>$mp_id, 'uid'=>$uid))->setfield('status', 4);
    }
	
    /**
     * 更新信息
     * @param unknown $mpId
     * @param unknown $data
     */
	public function updateInfo($mpId, $data=array()){
		return $this->where(array('mp_id'=>$mpId))->save($data);
	}
}
